import { action, computed, flow, makeObservable, observable } from "mobx"
import axios from "axios";
import Todo from "./todo";
export default class TodoStore {
    constructor() {
        this.todos = []
        this.filterCondition = "All"
        makeObservable(this, {
            todos: observable,
            addTodo: action.bound,
            loadTodos: flow.bound,
            removeId: action.bound,
            unCompletedTodosCount: computed,
            filterCondition: observable,
            changeFilterCondition: action.bound,
            filterTodos:computed,
            clearCompletedTodos:action.bound
        })
        this.loadTodos()
    }
    *loadTodos() {
        const result = yield axios.get("http://localhost:3001/todos");
        result.data.forEach(item => this.todos.push(new Todo(item)))
    }
    addTodo(title) {
        this.todos.push(new Todo({ title, id: this.createId() }))
    }
    createId() {
        if (!this.todos.length) return 1
        return this.todos.reduce((id, todo) => id < todo.id ? todo.id : id, 0) + 1
    }
    removeId(id) {
        this.todos = this.todos.filter(item => item.id !== id)
    }
    get unCompletedTodosCount() {
        return this.todos.filter(todo => !todo.isCompleted).length
    }
    changeFilterCondition(condition) {
        this.filterCondition = condition
    }
    get filterTodos() {
        switch (this.filterCondition) {
            case "active":
                return this.todos.filter(todo => !todo.isCompleted)
            case "completed":
                return this.todos.filter(todo => todo.isCompleted)
            default:
                return this.todos
        }
    }
    clearCompletedTodos() {
        this.todos = this.todos.filter(todo => !todo.isCompleted)
    }
}